<?php
// +----------------------------------------------------------------------
// | APP版本
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------
namespace app\event\app;

use app\common\event\Base;
use app\event\ucenter\User as UserEvent;
use app\model\app\CtripOrder as CtripOrderModel;
use app\model\app\JdGood as JdGoodModel;
use app\model\ucenter\User as UserModel;
use app\model\ucenter\UserMoneyLog as UserMoneyLogModel;
use app\model\ucenter\UserTask as UserTaskModel;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\helper\Str;

class Meituan extends Base
{


    private $APP_KEY = 'b50d4261ae0c4c5a8b7dccfc446d1bb3';
    private $APP_SECRET = '4aff4007f5e64717ae37924d2248682e';

    function curlPost($url, $post_data = array(), $timeout = 5, $header = "", $data_type = "")
    {
        $header = empty($header) ? '' : $header;
        //支持json数据数据提交
        if($data_type == 'json'){
            $post_string = json_encode($post_data);
        }elseif($data_type == 'array') {
            $post_string = $post_data;
        }elseif(is_array($post_data)){
            $post_string = http_build_query($post_data, '', '&');
        }
        $ch = curl_init();    // 启动一个CURL会话
        curl_setopt($ch, CURLOPT_URL, $url);     // 要访问的地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 对认证证书来源的检查   // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);     // Post提交的数据包
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);     // 设置超时限制防止死循环
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // 获取的信息以文件流的形式返回
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
        $result = curl_exec($ch);

        curl_close($ch);
        return $result;
    }
    /**
     * 获取签名头部字段
     * */
    public function getSignHeaders($config): array
    {
        // 获取当前时间的微秒数（浮点数，包含秒和小数部分的秒，小数部分代表微秒）
        $microtime = microtime(true);
        // 将微秒数转换为毫秒数
        $milliseconds = sprintf('%d', $microtime * 1000);
        $signHeaders = [
            'Content-Type:application/json',
            'S-Ca-App:' . $this->APP_KEY,
            'S-Ca-Timestamp:' . $milliseconds,
            'S-Ca-Signature-Headers:S-Ca-Timestamp,S-Ca-App',
            'Content-MD5:' . $this->contentMD5($config),
        ];
        $newSignHeaders = "S-Ca-App:" . $this->APP_KEY  . "\n" . 'S-Ca-Timestamp:' . $milliseconds . "\n";
        $signHeaders[] = 'S-Ca-Signature:' . $this->sign($config, $newSignHeaders);
        return $signHeaders;
    }

    public function sign($config, $signHeaders): string
    {
        $httpMethod = $config['method'];
        $contentMD5 = $this->contentMD5($config);
        $headers = $signHeaders;
        $url = $this->url($config);
        // 构建待签名的字符串
        $stringToSign = $httpMethod . "\n" . $contentMD5 . "\n" . $headers . $url;
        // 对HMAC签名进行Base64编码
        return base64_encode(hash_hmac('sha256', $stringToSign, $this->APP_SECRET, true));
    }

    public function contentMD5($config): string
    {
        // 检查是否为 POST 请求并且配置中包含数据
        if (isset($config['method']) && strtolower($config['method']) === 'post' && isset($config['data'])) {
            // 将数据转换为JSON字符串
            $jsonString = json_encode($config['data']);
            // 计算MD5哈希值（注意：md5函数默认返回哈希值的十六进制表示）
            $md5Hash = md5($jsonString, true); // 第二个参数true表示返回原始二进制数据
            // 对MD5哈希值进行Base64编码
            return base64_encode($md5Hash);
        } else {
            return '';
        }
    }

    public function url($config): string
    {
        // 提取 URL 路径部分
        $url = $config['url'];
        $path = '/' . implode('/', array_slice(explode('/', $url), 3));
        // 检查是否为 GET 请求并且配置中包含请求数据
        if (isset($config['method']) && strtolower($config['method']) === 'get' && isset($config['params'])) {
            // 对请求数据对象进行排序
            ksort($config['params']);
            $reqData = $config['params'];
            // 构建查询字符串
            $query = http_build_query($reqData);
            // 返回完整的 URL，包括查询字符串
            return $path . '?' . $query;
        } else {
            // 返回仅包含路径的 URL
            return $path;
        }
    }




}
